<template>
  <div class="work-order-distribute">
      <h2>派发工单</h2>

      <!-- 查询表单 -->
      <el-card class="search-card">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
              <el-form-item label="标题">
                  <el-input v-model="searchForm.title" placeholder="请输入工单标题（支持模糊）"></el-input>
              </el-form-item>
              <el-form-item label="编号">
                  <el-input v-model="searchForm.id" placeholder="请输入工单编号（支持模糊）"></el-input>
              </el-form-item>
              <el-form-item label="相关设备">
                  <el-input v-model="searchForm.device" placeholder="请输入相关设备（支持模糊）"></el-input>
              </el-form-item>
              <el-form-item label="创建时间">
                  <el-date-picker
                      v-model="searchForm.dateRange"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                  ></el-date-picker>
              </el-form-item>
              <el-form-item label="负责人">
                  <el-input v-model="searchForm.assignee" placeholder="请输入负责人（支持模糊）"></el-input>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" @click="handleSearch">查询</el-button>
                  <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
          </el-form>
      </el-card>

      <!-- 待派发工单表格 -->
      <el-card class="box-card">
          <template #header>
              <div class="card-header">
                  <span>待派发工单</span>
              </div>
          </template>
          <el-table
              :data="pendingWorkOrders"
              style="width: 100%"
              @selection-change="handleSelectionChange"
              ref="workOrderTable"
          >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="orderNum" label="编号" width="130"></el-table-column>
              <el-table-column prop="orderTitle" label="标题" width="200"></el-table-column>
              <el-table-column prop="orderType" label="类型" width="100"></el-table-column>
              <el-table-column prop="orderLeader" label="负责人" width="100"></el-table-column>
              <el-table-column prop="orderStatus" label="状态" width="100"></el-table-column>
              <el-table-column prop="deviceType" label="相关设备" width="120"></el-table-column>
              <el-table-column label="创建时间" width="160">
                  <template #default="scope">
                      {{ formatTime(scope.row.createTime) }}
                  </template>
              </el-table-column>
              <el-table-column label="更新时间" width="160">
                  <template #default="scope">
                      {{ formatTime(scope.row.updateTime) }}
                  </template>
              </el-table-column>
          </el-table>
      </el-card>

      <!-- 派发按钮 -->
      <div style="margin-top: 20px; text-align: right">
          <el-button type="primary" @click="openDistributeDialog" :disabled="selectedWorkOrderIds.length === 0">派发</el-button>
      </div>

      <!-- 派发确认弹窗 -->
      <el-dialog
          v-model="dialogVisible"
          title="确认派发"
          width="50%"
      >
          <el-form label-width="120px">
              <el-form-item label="工单编号">
                  <el-tag v-for="id in selectedWorkOrderIds" :key="id" style="margin-right: 10px">
                      {{ getOrderNumById(id) }}
                  </el-tag>
              </el-form-item>
              <el-form-item label="派发给" :required="true">
                  <el-input
                      v-model="distributeForm.assignee"
                      placeholder="请输入派发对象"
                  ></el-input>
               </el-form-item>
              <el-form-item label="预计总工时">
                 <el-input
                    v-model="distributeForm.estimatedHours"
                    placeholder="请输入预计总工时（选填）"
                    type="number"
                    min="0"
                >
                    <template #append>小时</template>
                </el-input>
             </el-form-item>
              <el-form-item v-if="selectedWorkOrderIds.length === 1" label="相关设备">
                  <el-input
                      v-model="singleWorkOrder.device"
                      placeholder="请输入相关设备"
                  ></el-input>
              </el-form-item>
              <el-form-item v-if="selectedWorkOrderIds.length === 1" label="设备位置">
                  <el-input
                      v-model="singleWorkOrder.location"
                      placeholder="请输入位置"
                  ></el-input>
              </el-form-item>
              <el-form-item v-if="selectedWorkOrderIds.length === 1" label="详细描述">
                  <el-input
                      v-model="singleWorkOrder.description"
                      type="textarea"
                      placeholder="请输入详细描述"
                  ></el-input>
              </el-form-item>
              <el-form-item label="参与人员">
                  <el-input
                      v-model="distributeForm.participants"
                      placeholder="请输入参与人员"
                  ></el-input>
              </el-form-item>
          </el-form>
          <template #footer>
              <span class="dialog-footer">
                  <el-button @click="dialogVisible = false">取消</el-button>
                  <el-button type="primary" @click="submitDistribute">确认派发</el-button>
              </span>
          </template>
      </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 查询表单数据
const searchForm = ref({
  id: '',
  title: '',
  device: '',
  assignee: '',
  dateRange: []
});

// 待派发工单列表
const pendingWorkOrders = ref<{ 
  orderNum: string;
  orderTitle: string;
  orderType: string;
  orderLeader: string;
  orderStatus: string;
  deviceType: string;
  createTime: string;
  updateTime: string;
  id: string;   //这个ID是啥。
  device: string; 
  location: string; 
  description: string; 
  assignee: string; 
  participants: string; 
}[]>([]);

// 表单数据
const distributeForm = ref({
  assignee: '',
  participants: '',
  remark: '',
  estimatedHours: null as number | null  // 新增字段
});

// 选中的工单ID列表
const selectedWorkOrderIds = ref<string[]>([]);

// 弹窗显示状态
const dialogVisible = ref(false);

// 表单引用
const workOrderTable = ref();

// 单个工单信息
const singleWorkOrder = ref({
  device: '',
  location: '',
  description: ''
});

// 从后端获取待派发工单数据
const fetchPendingWorkOrders = async () => {
  try {
      const params = {
          status: '待派发',
          id_like: searchForm.value.id,
          title_like: searchForm.value.title,
          device_like: searchForm.value.device,
          assignee: searchForm.value.assignee,
          startDate: searchForm.value.dateRange ? searchForm.value.dateRange[0] : null,
          endDate: searchForm.value.dateRange ? searchForm.value.dateRange[1] : null
      };

      const response = await axios.get('/api/repair-work-orders/search', {
          params: params
      });

      pendingWorkOrders.value = response.data;
  } catch (error) {
      console.error('Error fetching pending work orders:', error);
  }
};

// 当组件加载时获取数据
onMounted(() => {
  fetchPendingWorkOrders();
});

// 处理表格选择变化
const handleSelectionChange = (selection: { 
  orderNum: string;
  orderTitle: string;
  orderType: string;
  orderLeader: string;
  orderStatus: string;
  deviceType: string;
  createTime: string;
  updateTime: string;
  id: string; 
  device: string; 
  location: string; 
  description: string; 
  assignee: string; 
  participants: string; 
}[]) => {
  selectedWorkOrderIds.value = selection.map(item => item.id);
  if (selectedWorkOrderIds.value.length === 1) {
      const selectedOrder = selection[0];
      singleWorkOrder.value.device = selectedOrder.device;
      singleWorkOrder.value.location = selectedOrder.location;
      singleWorkOrder.value.description = selectedOrder.description;
      distributeForm.value.assignee = selectedOrder.assignee;
      distributeForm.value.participants = selectedOrder.participants;
  } else if (selectedWorkOrderIds.value.length > 1) {
      const firstOrder = selection[0];
      distributeForm.value.assignee = firstOrder.assignee;
      distributeForm.value.participants = firstOrder.participants;
  }
};

// 打开派发确认弹窗
const openDistributeDialog = () => {
  if (selectedWorkOrderIds.value.length === 0) {
      ElMessage.warning('请至少选择一个工单');
      return;
  }

  dialogVisible.value = true;
  if (selectedWorkOrderIds.value.length === 1) {
      const selectedOrder = pendingWorkOrders.value.find(order => order.id === selectedWorkOrderIds.value[0]);
      if (selectedOrder) {
          singleWorkOrder.value.device = selectedOrder.device;
          singleWorkOrder.value.location = selectedOrder.location;
          singleWorkOrder.value.description = selectedOrder.description;
          distributeForm.value.assignee = selectedOrder.assignee;
          distributeForm.value.participants = selectedOrder.participants;
      }
  } else if (selectedWorkOrderIds.value.length > 1) {
      const firstOrder = pendingWorkOrders.value.find(order => order.id === selectedWorkOrderIds.value[0]);
      if (firstOrder) {
          distributeForm.value.assignee = firstOrder.assignee;
          distributeForm.value.participants = firstOrder.participants;
      }
  }
};

// 提交派发
const submitDistribute = async () => {
  if (!distributeForm.value.assignee) {
      ElMessage.warning('请选择派发对象');
      return;
  }

  if (distributeForm.value.estimatedHours !== null && isNaN(Number(distributeForm.value.estimatedHours))) {
      ElMessage.warning('预计总工时必须为有效数字');
      return;
  }

  try {
      const workOrdersToUpdate = selectedWorkOrderIds.value.map(id => {
          const order = pendingWorkOrders.value.find(order => order.id === id);
          if (order) {
              return {
                  orderId: order.id,
                  orderLeader: distributeForm.value.assignee,
                  orderStatus: '待受理',
                  // 将 estimatedHours 转换为字符串格式
                  totalManHours: distributeForm.value.estimatedHours!== null? String(distributeForm.value.estimatedHours) : null,
                  ...(selectedWorkOrderIds.value.length === 1? {
                      deviceType: singleWorkOrder.value.device,
                      deviceLocation: singleWorkOrder.value.location,
                      faultDescription: singleWorkOrder.value.description,
                  } : {}),
                  orderParticipants: distributeForm.value.participants
              };
          }
          return null;
      }).filter(order => order!== null);

      await axios.put('/api/repair-work-orders/distribute', workOrdersToUpdate);

      ElMessage.success('工单派发成功！');
      dialogVisible.value = false;
      resetForm();
      fetchPendingWorkOrders();
  } catch (error) {
      console.error('Error submitting distribute:', error);
      ElMessage.error('工单派发失败，请稍后重试！');
  }
};

// 重置表单和选择
const resetForm = () => {
  distributeForm.value.assignee = '';
  distributeForm.value.estimatedHours = null;
  distributeForm.value.participants = '';
  distributeForm.value.remark = '';
  selectedWorkOrderIds.value = [];
  workOrderTable.value?.clearSelection();
  singleWorkOrder.value = {
      device: '',
      location: '',
      description: ''
  };
};

// 查询按钮点击事件
const handleSearch = () => {
  fetchPendingWorkOrders();
};

// 重置按钮点击事件
const resetSearch = () => {
  searchForm.value = {
      id: '',
      title: '',
      device: '',
      assignee: '',
      dateRange: []
  };
  fetchPendingWorkOrders();
};

// 格式化时间
const formatTime = (timeString: string) => {
  // 截取时间字符串，只保留到分钟
  return timeString.substring(0, 16);
};

// 根据工单ID获取工单编号
const getOrderNumById = (id: string) => {
  const order = pendingWorkOrders.value.find(order => order.id === id);
  return order ? order.orderNum : '';
};
</script>

<style scoped>
.work-order-distribute {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card {
  margin-bottom: 20px;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.el-form-item {
  margin-bottom: 10px;
}
</style>